import React, {Fragment, PureComponent} from 'react';
import {FormattedMessage} from 'umi-plugin-react/locale';
import {Avatar, Button, Form, Icon, Input, Menu, Modal, Progress, Spin, Tag} from 'antd';
import router from 'umi/router';
import moment from 'moment';
import groupBy from 'lodash/groupBy';
import { encode } from '@/utils/AesUtil';
import HeaderDropdown from '../HeaderDropdown';
import SystemInfo from '../SystemInfo';
import userInfoImg from '../../assets/userInfo.jpg'
import man from '../../assets/man.png'
import woman from '../../assets/woman.png'
import styles from './index.less';

const FormItem = Form.Item;

const formLayout = {
  labelCol: {span: 5},
  wrapperCol: {span: 18},
};

const userInfoSpan = {
  color: '#40a9ff',
  paddingBottom: '5px',
}

const userInfoP = {
  marginBottom: '10px',
}
const userInfoBg = {
  backgroundImage: 'url(' + userInfoImg + ')',
  backgroundRepeat: 'no-repeat',
  backgroundPosition: 'right center',
};

const CreateForm = Form.create()(props => {
  const {modalVisible, form, addDataFn, handleModalVisible, changePassword, pwdruleData, hasChange, logoutClick} = props;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      changePassword(fieldsValue);
    });
  };
  const suport = [];
  if (pwdruleData && pwdruleData.id && modalVisible) {
    if (pwdruleData.hasNumber) {
      suport.push('数字')
    }
    if (pwdruleData.hasUpper) {
      suport.push('大写字母')
    }
    if (pwdruleData.hasLower) {
      suport.push('小写字母')
    }
    if (pwdruleData.hasSpecial) {
      suport.push('特殊字符')
    }
  }
  const changePTip = () => {
    if (hasChange == 1) {
      // Modal.warning({title: '操作失败',content: '请先修改密码'});
      location.href = '/login'
      // router.push('/login');
      // logoutClick()
    } else {
      handleModalVisible()
    }
  }
  const handleValidator = (rule, val, callback) => {
    if (!val) {
      callback();
    }
    if (form.getFieldValue('oldPwd') == val) {
      callback('新密码不能和原密码相同');
    }
    callback();
  }
  const handleValidatorT = (rule, val, callback) => {
    if (!val) {
      callback();
    }
    if (form.getFieldValue('password') != val) {
      callback('确认密码应该和新密码相同');
    }
    callback();
  }
  return (
    <Modal
      destroyOnClose
      width={640}
      title='修改密码'
      visible={modalVisible}
      onOk={() => okHandle()}
      onCancel={() => changePTip()}
      footer={[
        <Button key="back" onClick={() => changePTip()}>返回</Button>,
        <Button key="go" type="primary" onClick={() => okHandle()}>确定</Button>
      ]}
      maskClosable={hasChange == 1 ? false : true}>
      <FormItem labelCol={{span: 5}} wrapperCol={{span: 19}} label="原密码">
        {form.getFieldDecorator('oldPwd', {
          rules: [{required: true, message: '原密码不能为空'}]
        })(<Input placeholder="请输入" type="password"/>)}
      </FormItem>
      <FormItem labelCol={{span: 5}} wrapperCol={{span: 19}} label="新密码">
        {form.getFieldDecorator('password', {
          rules: [{required: true, message: '新密码不能为空'}, {
            validator: handleValidator
          }]
        })(<Input placeholder="请输入" type="password"/>)}
      </FormItem>
      <FormItem labelCol={{span: 5}} wrapperCol={{span: 19}} label="确认密码">
        {form.getFieldDecorator('confirmPwd', {
          rules: [{required: true, message: '确认新密码不能为空'}, {
            validator: handleValidatorT
          }]
        })(<Input placeholder="请输入" type="password"/>)}
      </FormItem>
      <FormItem labelCol={{span: 5}} wrapperCol={{span: 19}} label="密码规则">
        {pwdruleData && pwdruleData.id && modalVisible &&
        <p style={{lineHeight: 2, marginTop: '6px'}}>
          长度为{pwdruleData.minLength}-{pwdruleData.maxLength}；<br/>
          {suport && suport.length ? <Fragment><span>必须包含{suport.map((v) => {
            return v
          }).join('、')}
          </span>；<br/></Fragment> : null}
          不能包含{pwdruleData.continuousLength}位以上的连续数字或字母。
        </p>}
      </FormItem>

    </Modal>
  );
});

export default class GlobalHeaderRight extends PureComponent {
  state = {
    modalVisible: false,
    editPassTip: false,
    pwdruleData: {}, //密码规则
  }

  getNoticeData() {
    const {notices = []} = this.props;
    if (notices.length === 0) {
      return {};
    }
    const newNotices = notices && typeof(notices) == 'Object' && notices.length && notices.map(notice => {
      const newNotice = {...notice};
      if (newNotice.datetime) {
        newNotice.datetime = moment(notice.datetime).fromNow();
      }
      if (newNotice.id) {
        newNotice.key = newNotice.id;
      }
      if (newNotice.extra && newNotice.status) {
        const color = {
          todo: '',
          processing: 'blue',
          urgent: 'red',
          doing: 'gold',
        }[newNotice.status];
        newNotice.extra = (
          <Tag color={color} style={{marginRight: 0}}>
            {newNotice.extra}
          </Tag>
        );
      }
      return newNotice;
    });
    return groupBy(newNotices, 'type');
  }

  getUnreadData = noticeData => {
    const unreadMsg = {};
    Object.entries(noticeData).forEach(([key, value]) => {
      if (!unreadMsg[key]) {
        unreadMsg[key] = 0;
      }
      if (Array.isArray(value)) {
        unreadMsg[key] = value.filter(item => !item.read).length;
      }
    });
    return unreadMsg;
  };

  changeReadState = clickedItem => {
    const {id} = clickedItem;
    const {dispatch} = this.props;
    dispatch({
      type: 'global/changeNoticeReadState',
      payload: id,
    });
  };



  changePassword =async data => {
    let password = await encode(data.password);
    let confirmPwd = await encode(data.confirmPwd);
    let oldPwd = await encode(data.oldPwd);
    const params = {
      password,
      confirmPwd,
      oldPwd,
    }
    const {dispatch} = this.props;
    dispatch({
      type: 'user/changePassword',
      payload: params,
      callback: (res) => {
        if (res.result == "ok") {
          Modal.success({
            title: res.msg, onOk: () => {
              router.push('/login');
            }
          });
          this.handleModalVisible();
        } else {
          Modal.error({title: '操作失败', content: res.msg});
        }
      },
    });
  }

  pwdrule = data => {
    const {dispatch} = this.props;
    dispatch({
      type: 'user/pwdruleF',
      callback: (res) => {
        if (res.result == "ok") {
          this.setState({
            pwdruleData: res.data,
          })
        }
      },
    });
  }

  logoutClick = () => {
    const {dispatch} = this.props;
    dispatch({
      type: 'login/removeToken',
      callback: (res) => {
        // if (res.result == "ok") {
        //
        // } else {
        //   Modal.error({title: '操作失败', content: "退出失败"});
        // }
      },
    });

    dispatch({
      type: 'login/logout',
    });


  }

  handleModalVisible = (flag) => {
    this.setState({
      modalVisible: !!flag,
      editPassTip: true,
    });
    if (flag) {
      this.pwdrule();
    }
  };

  handleDetailModalVisible = (flag) => {
    this.setState({
      detailModalVisible: !!flag,
    });
  };

  componentDidMount() {
    const that = this;
    setTimeout(function () {
      const {currentUser} = that.props;
      const pwdEdit = currentUser.pwdEdit;
      const pwdEditWarning = currentUser.pwdEditWarning;
      const pwdWarningDays = currentUser.pwdWarningDays;
      if (pwdEdit == 0 && pwdEditWarning == 1) {
        Modal.confirm({
          title: '密码还有' + pwdWarningDays + '天过期',
          okText: '修改',
          cancelText: '取消',
          onOk: () => {
            that.handleModalVisible(true)
          }
        })
      }
    }, 500);
    this.queryUserfilespace()
  }

  // 进度条--使用空间
  queryUserfilespace = () => {
    const {dispatch} = this.props;
    dispatch({
      type: 'user/queryUFS',
    });
  }

  render() {
    const {
      currentUser,
      fetchingNotices,
      onNoticeVisibleChange,
      onMenuClick,
      logoutClick,
      onNoticeClear,
      theme,
      percentage,
    } = this.props;
    const menu = (
      <Menu className={styles.menu} selectedKeys={[]} onClick={onMenuClick}>

        {/* <Menu.Item key="changerpass" onClick={() => this.handleModalVisible(true)}>
          <Icon type="lock"/>
          <FormattedMessage id="menu.account.changePass" defaultMessage="Change Password"/>
        </Menu.Item> */}

        <Menu.Item key="userInfo" onClick={() => this.handleDetailModalVisible(true)}>
          <Icon type="user"/>
          <FormattedMessage id="menu.account.info" defaultMessage="Personal information"/>
        </Menu.Item>
        {
          // <Menu.Item key="userinfo">
          //   <Icon type="setting" />
          //   <FormattedMessage id="menu.account.settings" defaultMessage="account settings" />
          // </Menu.Item>
          // <Menu.Item key="triggerError">
          //   <Icon type="close-circle" />
          //   <FormattedMessage id="menu.account.trigger" defaultMessage="Trigger Error" />
          // </Menu.Item>
        }
        {/* <Menu.Divider/>
        <Menu.Item key="logout">
          <Icon type="logout"/>
          <FormattedMessage id="menu.account.logout" defaultMessage="logout"/>
        </Menu.Item>*/}
      </Menu>
    );
    const noticeData = this.getNoticeData();
    const unreadMsg = this.getUnreadData(noticeData);
    let className = styles.right;
    if (theme === 'dark') {
      className = `${styles.right}  ${styles.dark}`;
    }
    const parentMethods = {
      handleModalVisible: this.handleModalVisible,
      changePassword: this.changePassword,
      logoutClick: this.logoutClick,
    };
    const detailsMethods = {
      handleDetailModalVisible: this.handleDetailModalVisible,
    };
    const {modalVisible, editPassTip, detailModalVisible, pwdruleData} = this.state;
    //如果需要修改密码，并且未提示过修改密码
    if (currentUser.pwdEdit == 1 && !editPassTip) {
      this.handleModalVisible(true);
    }
    let userSpance;
    if (currentUser.userCode == 'sysadmin' || currentUser.userCode == 'secadmin' || currentUser.userCode == 'auditadmin') {
      userSpance = null;
    } else {
      //
      let title = "使用空间";
      if (percentage > 99) {
        title = "使用空间已满";
      }


      userSpance = <a className={styles.action} title={title}>
        <Progress style={{width: '140px'}} percent={parseInt(percentage < 1 ? 1 : percentage)}
                  status={percentage > 99 ? 'exception' : ''}/>
      </a>
    }


    return (
      <div className={className}>
        <CreateForm {...parentMethods} modalVisible={modalVisible} hasChange={currentUser.pwdEdit}
                    pwdruleData={pwdruleData}/>

        {userSpance}

        {currentUser.userCode ? (
          <UserInfoBox {...detailsMethods} detailModalVisible={detailModalVisible} detailsData={currentUser}/>
        ) : null}
        {currentUser.userCode ? (
          <HeaderDropdown overlay={menu}>
            <span className={`${styles.action} ${styles.account}`}>
              <Avatar
                size="small"
                className={styles.avatar}
                src={currentUser.sex == 0 ? woman : man}
                alt="avatar"
              />
              <span className={styles.name}>{currentUser.userName}</span>
            </span>
          </HeaderDropdown>
        ) : (
          <Spin size="small" style={{marginLeft: 8, marginRight: 8}}/>
        )}

        {
          // <HeaderSearch
          //   className={`${styles.action} ${styles.search}`}
          //   placeholder={formatMessage({ id: 'component.globalHeader.search' })}
          //   dataSource={[
          //     formatMessage({ id: 'component.globalHeader.search.example1' }),
          //     formatMessage({ id: 'component.globalHeader.search.example2' }),
          //     formatMessage({ id: 'component.globalHeader.search.example3' }),
          //   ]}
          //   onSearch={value => {
          //     console.log('input', value); // eslint-disable-line
          //   }}
          //   onPressEnter={value => {
          //     console.log('enter', value); // eslint-disable-line
          //   }}
          // />
        }

        {/*<Tooltip title={formatMessage({ id: 'component.globalHeader.help' })}>
          <a
            target="_blank"
            href="https://pro.ant.design/docs/getting-started"
            rel="noopener noreferrer"
            className={styles.action}
          >
            <Icon type="question-circle-o" />
          </a>
        </Tooltip>*/}

          {/* <a
            href="/sdk/help.html"
            target="blank"
          >
            SDK操作流程
          </a> */}

        <a className={styles.action} title="版本信息">
          <SystemInfo/>
        </a>

        <a key="logout" onClick={() => this.logoutClick()} className={styles.action} title="退出">
          <Icon type="logout" style={{color: 'red', fontSize: '18px'}}/>
        </a>


        {
          // <NoticeIcon
          //   className={styles.action}
          //   count={currentUser.unreadCount}
          //   onItemClick={(item, tabProps) => {
          //     console.log(item, tabProps); // eslint-disable-line
          //     this.changeReadState(item, tabProps);
          //   }}
          //   loading={fetchingNotices}
          //   locale={{
          //     emptyText: formatMessage({ id: 'component.noticeIcon.empty' }),
          //     clear: formatMessage({ id: 'component.noticeIcon.clear' }),
          //     viewMore: formatMessage({ id: 'component.noticeIcon.view-more' }),
          //     notification: formatMessage({ id: 'component.globalHeader.notification' }),
          //     message: formatMessage({ id: 'component.globalHeader.message' }),
          //     event: formatMessage({ id: 'component.globalHeader.event' }),
          //   }}
          //   onClear={onNoticeClear}
          //   onPopupVisibleChange={onNoticeVisibleChange}
          //   onViewMore={() => message.info('Click on view more')}
          //   clearClose
          // >
          //   <NoticeIcon.Tab
          //     count={unreadMsg.notification}
          //     list={noticeData.notification}
          //     title="notification"
          //     emptyText={formatMessage({ id: 'component.globalHeader.notification.empty' })}
          //     emptyImage="https://gw.alipayobjects.com/zos/rmsportal/wAhyIChODzsoKIOBHcBk.svg"
          //     showViewMore
          //   />
          //   <NoticeIcon.Tab
          //     count={unreadMsg.message}
          //     list={noticeData.message}
          //     title="message"
          //     emptyText={formatMessage({ id: 'component.globalHeader.message.empty' })}
          //     emptyImage="https://gw.alipayobjects.com/zos/rmsportal/sAuJeJzSKbUmHfBQRzmZ.svg"
          //     showViewMore
          //   />
          //   <NoticeIcon.Tab
          //     count={unreadMsg.event}
          //     list={noticeData.event}
          //     title="event"
          //     emptyText={formatMessage({ id: 'component.globalHeader.event.empty' })}
          //     emptyImage="https://gw.alipayobjects.com/zos/rmsportal/HsIsxMZiWKrNUavQUXqx.svg"
          //     showViewMore
          //   />
          // </NoticeIcon>
        }

        {/*  <SelectLang className={styles.action} />       */}
      </div>
    );
  }
}

class UserInfoBox extends PureComponent {
  constructor(props) {
    super(props);
  }

  render() {
    const {detailModalVisible, handleDetailModalVisible, detailsData} = this.props;
    return (
      <Modal
        destroyOnClose
        width={450}
        title="查看个人信息15195911338 15195911338"
        visible={detailModalVisible}
        onCancel={() => handleDetailModalVisible(false)}
        footer={[
          <Button key="back" type="primary" onClick={() => handleDetailModalVisible()}>返回</Button>
        ]}
        bodyStyle={userInfoBg}
      >
        <Fragment>
          <p style={userInfoP}><span style={userInfoSpan}>用户名</span><br/>{detailsData.userName}</p>
          <p style={userInfoP}><span style={userInfoSpan}>手机号</span><br/>{detailsData.mobilePhone}</p>
          <p style={userInfoP}><span style={userInfoSpan}>邮箱</span><br/>{detailsData.email}</p>
          <p style={userInfoP}><span style={userInfoSpan}>角色</span><br/>{detailsData.roleName}</p>
        </Fragment>
      </Modal>
    );
  }
}
